﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace AttachScreenShotToJira.CODE.CORE_LOGIC
{
    class JIRA_UPLOAD
    {
        //from http://www.codeproject.com/Tips/828384/Creating-an-Issue-with-Multiple-Attachments-in-Jir
        public static string AddAttachment(string issueKey, string filename)
        {
            try
            {
                HttpWebResponse response = null;
                HttpWebRequest request = null;

                //create the restURL
                string restUrl = String.Format("{0}rest/api/2/issue/{1}/attachments", Properties.Settings.Default.sJiraServer, issueKey);

                //start stream
                String boundary = String.Format("----------{0:N}", Guid.NewGuid());
                var stream = new MemoryStream();
                var writer = new StreamWriter(stream);

                //read the file
                var fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                var data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();

                //write content to stream
                writer.WriteLine("--{0}", boundary);
                writer.WriteLine("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", Path.GetFileName(filename));
                writer.WriteLine("Content-Type: application/octet-stream");
                writer.WriteLine();
                writer.Flush();
                stream.Write(data, 0, data.Length);
                writer.WriteLine();

                //lclosing
                writer.WriteLine("--" + boundary + "--");
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                //create request
                request = WebRequest.Create(restUrl) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                request.Accept = "application/json";

                //authenticate
                request.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());
                request.Headers.Add("X-Atlassian-Token", "nocheck");
                request.ContentLength = stream.Length;


                using (Stream requestStream = request.GetRequestStream())
                {
                    stream.WriteTo(requestStream);
                    requestStream.Close();
                }

                using (response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var reader = new StreamReader(response.GetResponseStream());
                        return String.Format("The server returned '{0}'\n{1}", response.StatusCode, reader.ReadToEnd());
                    }
                }
                request.Abort();

                return "";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        //encode credentials
        private static string GetEncodedCredentials()
        {
            string UserName = Properties.Settings.Default.sUsername;
            string Password = Properties.Settings.Default.sPassword;

            string mergedCredentials = String.Format("{0}:{1}", UserName, Password);
            byte[] byteCredentials = Encoding.UTF8.GetBytes(mergedCredentials);
            return Convert.ToBase64String(byteCredentials);
        }
    }
}
